<?php

/**
 * Created by PhpStorm.
 * Script Name: Setting.php
 * Create: 2020/5/24 上午10:25
 * Description: 站点配置
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\admin\controller;
use app\common\model\Reply as ReplyM;
use app\constants\Common;
use app\constants\Media;
use app\constants\Reply as ReplyConst;
use app\constants\Bot as BotConst;

class Reply extends Botbase
{
    /**
     * @var ReplyM
     */
    protected $model;
    private $tabList;
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new ReplyM();
        $events = ReplyConst::events();
        foreach ($events as $k => $v){
            $this->tabList[$k] = [
                'title' => $events[$k],
                'href' => url('index', ['event' => $k])
            ];
        }
    }

    /**
     *
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function copy()
    {
        if(request()->isPost()){
            $post_data = input('post.');
            $exists = $this->model->getField(['media_id'], ['bot_id' => $this->bot['id']]);
            $list = $this->model->getAll([
                'where' => ['bot_id' => $post_data['bot_id'], 'status' => 1, 'media_id' => ['notin', $exists]],
                'refresh' => true
            ]);
            foreach ($list as $v){
                unset($v['id']);
                $v['bot_id'] = $this->bot['id'];
                $v['wxids'] = '';
                $this->model->addOne($v);
            }
            $this->success('操作成功');
        }
        $bot_list = $this->getBots(['id' => ['<>', $this->bot['id']]]);
        // 使用FormBuilder快速建立表单页面
        $builder = new FormBuilder();
        $builder->setMetaTitle('复制内容')
            ->setPostUrl(url('copy'))
            ->addFormItem('bot_id', 'chosen', '机器人', '请选择', $bot_list, 'required');

        return $builder->show();
    }

    /**
     * 设置
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function index(){
        $current_name = input('event', ReplyConst::BEADDED);
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = ['bot_id' => $this->bot['id'], 'event' => $current_name];
            $total = $this->model->total($where, true);
            if ($total) {
                $list = $this->model->getList(
                    [$post_data['page'], $post_data['limit']], $where,
                    ['sort' => 'desc'], true, true
                );
                foreach ($list as $k => $v){
                    $v['media_id'] && $v = array_merge(model('media_'.$v['media_type'])->getOne(['id' => $v['media_id'], 'admin_id' => $this->adminInfo['id']])->toArray(), $v->toArray());
                    $list[$k] = $v;
                }
            } else {
                $list = [];
            }
            $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setTabNav($this->tabList, $current_name)
            ->setDataUrl(url('index', ['event' => $current_name]))
            ->addTopButton('addnew', ['title' => '新增消息响应','href' => url('add', ['event' => $current_name])])
            ->addTableColumn(['title' => '消息类型', 'field' => 'msg_type', 'type' => 'enum','options'=>BotConst::msgTypes(),'minWidth' => 80])
            ->addTableColumn(['title' => '响应类型', 'field' => 'handle_type', 'type' => 'enum','options'=>ReplyConst::handleTypes(),'minWidth' => 80])
            ->addTableColumn(['title' => '回复类型', 'field' => 'media_type', 'type' => 'enum','options'=>Media::types(),'minWidth' => 80])
            ->addTableColumn(['title' => '内容名称', 'field' => 'title', 'minWidth' => 80]);
        switch ($current_name){
            case Media::IMAGE:
                $builder->addTableColumn(['title' => '图片', 'field' => 'url', 'minWidth' => 100]);
                break;
            case Media::FILE:
                $builder->addTableColumn(['title' => '文件', 'field' => 'url', 'minWidth' => 200]);
                break;
            case Media::VIDEO:
                $builder->addTableColumn(['title' => '视频', 'field' => 'url', 'minWidth' => 200]);
                break;
            default:
                $builder->addTableColumn(['title' => '内容', 'field' => 'content', 'minWidth' => 200]);
                break;
        }
        $builder->addTableColumn(['title' => '优先级', 'field' => 'sort', 'minWidth' => 80])
            ->addTableColumn(['title' => '状态', 'field' => 'status', 'minWidth' => 80,'type' => 'switch','options' => Common::status()])
            ->addTableColumn(['title' => '操作', 'minWidth' => 150, 'type' => 'toolbar'])
            ->addRightButton('edit')
            ->addRightButton('delete', ['title'=>'移除']);

        if($current_name == ReplyConst::MSG){
            $builder->addTopButton('addnew', ['title' => '新增动作响应','href' => url('eventAdd', ['event' => $current_name])]);
        }
        return $builder->show();
    }

    public function savePost($jump_to = '/undefined', $data = [])
    {
        $post_data = input('post.');
        if(isset($post_data['media_id']) && empty($post_data['media_id'])){
            $this->error('请选择素材');
        }

        if(empty($post_data[$this->pk])){
            $res = $this->model->addOne($post_data);
        }else {
            $res = $this->model->updateOne($post_data);
        }

        if($res){
            $where = [
                'bot_id' => $this->bot['id'],
                'event' => $res['event'],
                'status' => 1
            ];
            isset($res['msg_type']) && $where['msg_type'] = $res['msg_type'];
            $this->model->getAll([
                'order' => ['sort' => 'desc'],
                'where' => $where,
                'refresh' => true
            ]);
            $this->success('数据保存成功', $jump_to);
        }else{
            $this->error('数据保存出错');
        }
    }

    /**
     * 编辑消息响应
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function edit(){
        $id = input('id', null);
        $reply = $this->model->getOneByMap(['id' => $id, 'bot_id' => $this->bot['id']], true, true);

        if (!$reply) {
            $this->error('参数错误');
        }

        if($reply['event'] == ReplyConst::MSG && $reply['handle_type'] != ReplyConst::HANDLE_MSG){
            $this->redirect(url('eventEdit', ['id' => $id]));
        }

        $material = model('media_' . $reply['media_type'])->getOneByMap([
            'admin_id' => $reply['admin_id'],
            'id' => $reply['media_id']
        ], true, true);
        if(!empty($reply['wxids'])){
            $reply['wxids'] = explode(',', $reply['wxids']);
        }

        $builder = new FormBuilder();

        $builder->setPostUrl(url('savePost'))
            ->addFormItem('id', 'hidden', 'id', 'id')
            ->setFormData($reply);
        switch ($reply['event']){
            case ReplyConst::FRIEND_IN:
                $groups = $this->getGroups();
                $builder->addFormItem('wxids', 'chosen_multi', '指定群', '指定群', $groups, 'required')
                    ->addFormItem('need_at', 'radio', '艾特新人', '艾特新人', [0 => '否', 1 => '是'], 'required');
                break;
            case ReplyConst::MSG:
                $builder->addFormItem('msg_type', 'select', '消息类型', '接收到的消息类型', \app\constants\Bot::msgTypes())
                    ->addFormItem('wxids', 'chosen_multi', '指定对象', '指定对象', $this->getMembers(), 'required');
                break;
        }
        return $builder->addFormItem('media', 'choose_media', '回复内容', '回复内容', ['types' => \app\constants\Media::types(), 'id' => $reply['media_id'], 'type' => $reply['media_type']], 'required')
            ->addFormItem('sort', 'number', '排序', '排序', [], 'required min=0')
            ->addFormItem('status', 'radio', '状态', '状态', [1 => '启用', 0 => '禁用'], 'required')
            ->show(['material' => $material]);
    }

    /**
     * 新增消息响应
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function add(){
        $current_name = input('event', ReplyConst::BEADDED);
        $builder = new FormBuilder();
        $material = [];

        $data = [
            'admin_id' => $this->adminInfo['id'],
            'bot_id' => $this->bot['id'],
            'event' => $current_name,
            'status' => 1,
            'handle_type' => ReplyConst::HANDLE_MSG
        ];
        $builder->setPostUrl(url('savePost'))
            ->setTip("添加【".ReplyConst::events($current_name)."】回复")
            ->addFormItem('admin_id', 'hidden', 'adminid', 'adminid')
            ->addFormItem('bot_id', 'hidden', 'botid', 'botid')
            ->addFormItem('event', 'hidden', 'event', 'event')
            ->addFormItem('handle_type', 'hidden', 'handle_type', 'handle_type');

        switch ($current_name){
            case ReplyConst::FRIEND_IN:
                $data['need_at'] = 0;
                $groups = $this->getGroups();
                $builder->addFormItem('wxids', 'chosen_multi', '指定群', '对指定群起作用', $groups, 'required')
                    ->addFormItem('need_at', 'radio', '艾特新人', '艾特新人', [0 => '否', 1 => '是'], 'required');
                break;
            case ReplyConst::MSG:
                $builder->addFormItem('msg_type', 'select', '消息类型', '接收到的消息类型', \app\constants\Bot::msgTypes())
                    ->addFormItem('wxids', 'chosen_multi', '指定对象', '指定对象', $this->getMembers(), 'required');
                break;
        }
        return $builder->addFormItem('media', 'choose_media', '回复内容', '回复内容', ['types' => \app\constants\Media::types()], 'required')
            ->addFormItem('sort', 'number', '排序', '数字越大优先级越高', [], 'required min=0')
            ->addFormItem('status', 'radio', '状态', '状态', [1 => '启用', 0 => '禁用'], 'required')
            ->setFormData($data)
            ->show(['material' => $material]);
    }

    /**
     * 新增动作响应
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function eventAdd(){
        $current_name = input('event', ReplyConst::MSG);
        $builder = new FormBuilder();
        $data = [
            'admin_id' => $this->adminInfo['id'],
            'bot_id' => $this->bot['id'],
            'event' => $current_name,
            'status' => 1
        ];
        $builder->setPostUrl(url('savePost'))
            ->setTip("添加【".ReplyConst::events($current_name)."】的响应动作")
            ->addFormItem('admin_id', 'hidden', 'adminid', 'adminid')
            ->addFormItem('bot_id', 'hidden', 'botid', 'botid')
            ->addFormItem('event', 'hidden', 'event', 'event')
            ->addFormItem('msg_type', 'select', '消息类型', '接收到的消息类型', \app\constants\Bot::msgTypes())
            ->addFormItem('wxids', 'chosen_multi', '指定对象', '对指定好友或群起作用', $this->getMembers(), 'required')
            ->addFormItem('handle_type', 'select', '响应动作', '删除好友对私聊起作用，移出群对群聊起作用', ReplyConst::actionTypes())
            ->addFormItem('sort', 'number', '排序', '数字越大优先级越高', [], 'required min=0')
            ->addFormItem('status', 'radio', '状态', '状态', [1 => '启用', 0 => '禁用'], 'required')
            ->setFormData($data);

        return $builder->show();
    }


    public function eventEdit(){
        $id = input('id', null);
        $reply = $this->model->getOneByMap(['id' => $id, 'bot_id' => $this->bot['id']], true, true);

        if (!$reply) {
            $this->error('参数错误');
        }

        if(!empty($reply['wxids'])){
            $reply['wxids'] = explode(',', $reply['wxids']);
        }

        $builder = new FormBuilder();
        $builder->setPostUrl(url('savePost'))
            ->addFormItem('id', 'hidden', 'id', 'id')
            ->addFormItem('msg_type', 'select', '消息类型', '接收到的消息类型', \app\constants\Bot::msgTypes())
            ->addFormItem('wxids', 'chosen_multi', '指定对象', '对指定好友或群起作用', $this->getMembers(), 'required')
            ->addFormItem('handle_type', 'select', '响应动作', '删除好友对私聊起作用，移出群对群聊起作用', ReplyConst::actionTypes())
            ->addFormItem('sort', 'number', '排序', '数字越大优先级越高', [], 'required min=0')
            ->addFormItem('status', 'radio', '状态', '状态', [1 => '启用', 0 => '禁用'], 'required')
            ->setFormData($reply);

        return $builder->show();
    }
}